<template>
  <view class="createChat">
    <z-paging ref="paging" v-model="dataList" @query="queryList">
      <view class="createChatBox">
        <uv-tabs
          :list="cardsList"
          @change="handerChange"
          :itemWidth="180"
          :scrollable="false"
          :activeStyle="{
            color: 'var(--text-active-primary)',
            fontWeight: '600',
            fontSize: '32rpx',
            transform: 'scale(1.1)',
            transition: 'all 0.3s ease',
          }"
          :inactiveStyle="{
            color: 'var(--text-regular)',
            fontSize: '28rpx',
            transform: 'scale(1)',
            transition: 'all 0.3s ease',
          }"
          lineColor="var(--text-active-primary)"
          lineWidth="30"
          lineHeight="2"
          itemStyle="padding-left: 15px; padding-right: 15px; height: 80rpx;"
        ></uv-tabs>
        <uv-modal
          ref="modalRef"
          title="请选择创建方式"
          content="角色卡首次通过审核后，赠送51元大礼包（200次经济模式+50次魅惑+3000🟡）"
        >
          <template v-slot:confirmButton>
            <view class="modalSelectBox">
              <uv-button
                type="primary"
                color="var(--text-active-primary)"
                @click="openCreateModal"
                text="手动创建"
              />
              <uv-button
                type="primary"
                color="var(--text-active-primary)"
                class="exportDataStyle"
                @click="exportData"
                text="导入角色"
              />
            </view>
          </template>
        </uv-modal>
        <view class="createChatHead">
          <uv-button
            type="primary"
            color="var(--text-active-primary)"
            text="创建"
            @click="openModal"
          ></uv-button>
        </view>
        <view class="list-card">
          <template v-if="dataList.length">
            <CardItem
              v-for="(card, index) in dataList"
              :key="card.role_id"
              :data="card"
              :index="index"
              type="private"
              @click="onCardClick"
              @publish="onPublish"
            />
          </template>
          <template v-else>
            <text class="noData">你还没有创建的角色卡片，请点击创建或者上传</text>
          </template>
        </view>
      </view>
    </z-paging>
    <uv-popup
      ref="popupRef"
      mode="bottom"
      :zIndex="99990"
      :closeable="true"
      :closeOnClickOverlay="false"
    >
      <view class="popupCreateBox">
        <uv-form
          labelPosition="top"
          labelWidth="auto"
          class="popupCreateForm"
          :model="formData"
          ref="form"
          :borderBottom="false"
        >
          <uv-form-item label="角色卡名称" required prop="userData.card_name">
            <uv-input
              v-model="formData.userData.card_name"
              placeholder="请填写"
              class="baseInputHeight borderBox"
              border="none"
            ></uv-input>
          </uv-form-item>
          <uv-form-item label="AI角色名" required prop="userData.role_name">
            <uv-input
              v-model="formData.userData.role_name"
              placeholder="请填写"
              class="baseInputHeight borderBox"
              border="none"
            ></uv-input>
          </uv-form-item>
          <uv-form-item label="用户角色名" required prop="userData.user_name">
            <uv-input
              v-model="formData.userData.user_name"
              placeholder="请填写"
              class="baseInputHeight borderBox"
              border="none"
            ></uv-input>
          </uv-form-item>
          <uv-form-item label="玩法类型" prop="userData.model">
            <uv-radio-group
              v-model="formData.userData.model"
              inactiveColor="var(--info-color)"
              activeColor="var(--text-active-primary)"
              labelColor="var(--color-background-lighter)"
            >
              <uv-radio
                style="margin: 0 0.3rem"
                v-for="item in modelList"
                :key="item"
                :label="item"
                :name="item"
              ></uv-radio>
            </uv-radio-group>
          </uv-form-item>
          <uv-form-item label="会长" required prop="userData.author">
            <uv-input
              v-model="formData.userData.author"
              placeholder="请填写"
              class="baseInputHeight borderBox"
              border="none"
            ></uv-input>
          </uv-form-item>
          <uv-form-item label="剧情" prop="userData.description">
            <uv-textarea
              v-model="formData.userData.description"
              placeholder="请填写"
              class="borderBox"
              border="none"
            ></uv-textarea>
          </uv-form-item>
          <uv-form-item label="个性" prop="userData.personality">
            <uv-textarea
              v-model="formData.userData.personality"
              placeholder="请填写"
              class="borderBox"
              border="none"
            ></uv-textarea>
          </uv-form-item>
          <uv-form-item label="示例" prop="userData.mes_example">
            <uv-textarea
              v-model="formData.userData.mes_example"
              placeholder="请填写"
              class="borderBox"
              border="none"
            ></uv-textarea>
          </uv-form-item>
          <uv-form-item label="场景" prop="userData.scenario">
            <uv-textarea
              v-model="formData.userData.scenario"
              placeholder="请填写"
              class="borderBox"
              border="none"
            ></uv-textarea>
          </uv-form-item>
          <uv-form-item label="开场白" prop="userData.first_mes">
            <uv-textarea
              v-model="formData.userData.first_mes"
              placeholder="请填写"
              class="borderBox"
              border="none"
            ></uv-textarea>
          </uv-form-item>
          <uv-form-item label="世界书" prop="userData.character_book">
            <uv-textarea
              v-model="formData.userData.character_book"
              placeholder="请填写"
              class="borderBox"
              border="none"
            ></uv-textarea>
          </uv-form-item>
        </uv-form>
        <uv-button
          type="primary"
          color="var(--text-active-primary)"
          class="popupCreateEmit"
          text="提交"
          customStyle="margin-top: 10px"
          @click="submit"
        ></uv-button>
      </view>
    </uv-popup>
  </view>
</template>
<script setup lang="ts">
import { ref, reactive } from "vue";
import RoleAPI from "@/api/role";
import CardItem from "@/components/TBMComponents/components/CardsItem/index.vue";
import { useCardsStore } from "@/store/index";

const cardsStore = useCardsStore();
const cardsList = ref([
  {
    name: "创建私有卡",
    key: "cards",
  },
  {
    name: "创建私有群",
    key: "groups",
  },
]);

const paging = ref<any>(null);
const dataList = ref<any[]>([]);
const modalRef = ref<any>(null);
const popupRef = ref<any>(null);
const form = ref<any>(null);
const modelList = ["轻聊天", "角色扮演", "全知视角"];
const type = ref(0); // 0-手动创建角色 1-导入角色卡
const formData = reactive({
  userData: {
    card_name: "",
    role_name: "",
    user_name: "",
    model: "", // 轻聊天 角色扮演 全知视角
    author: "",
    description: "",
    personality: "",
    mes_example: "",
    scenario: "",
    first_mes: "",
    character_book: "",
  },
});

// const rules = {
//   "userData.card_name": {
//     type: "string",
//     required: true,
//     message: "请填写",
//     trigger: ["blur"],
//   },
//   "userData.role_name": {
//     type: "string",
//     required: true,
//     message: "请填写",
//     trigger: ["blur"],
//   },
//   "userData.user_name": {
//     type: "string",
//     required: true,
//     message: "请填写",
//     trigger: ["blur"],
//   },
// };

const onCardClick = (card: any) => {
  console.log("点击了卡片：", card);
  cardsStore.setCurrentCard(card);
  uni.navigateTo({
    url: "/pages/cardsDetail/index",
  });
};

const onPublish = (card: any) => {
  console.log("onPublish：", card);
};

// @query所绑定的方法不要自己调用！！需要刷新列表数据时，只需要调用paging.value.reload()即可
const queryList = (pageNum: number, pageSize: number) => {
  // 组件加载时会自动触发此方法，因此默认页面加载时会自动触发，无需手动调用
  // 这里的pageNo和pageSize会自动计算好，直接传给服务器即可
  // 模拟请求服务器获取分页数据，请替换成自己的网络请求

  // 模拟数据
  const params = {
    start: (pageNum - 1) * pageSize, // 从第N条开始
    size: pageSize, // 每次查多少条
  };
  RoleAPI.getPage(params)
    .then((res: any) => {
      paging.value.complete(res.data);
    })
    .catch((err) => {
      paging.value.complete(false);
    });
};

const submit = () => {
  uni.showLoading({
    title: "加载中",
    mask: true,
  });
  form.value
    .validate()
    .then(() => {
      RoleAPI.add({ ...formData.userData, type: type.value }).then((res) => {
        uni.hideLoading();
        // paging.value.reload()
        popupRef.value.close();
        modalRef.value.close();
        setTimeout(() => {
          uni.showToast({
            title: "创建成功，等待审核！",
            duration: 2000,
          });
        }, 10);
      });
    })
    .catch(() => {
      uni.showToast({
        title: "请填写！",
        duration: 2000,
      });
    });
};

const exportData = () => {
  type.value = 1;
  uni.chooseImage({
    count: 1,
    success: (chooseImageRes) => {
      const tempFilePaths = chooseImageRes.tempFilePaths;
      uni.showLoading({
        title: "加载中",
        mask: true,
      });
      RoleAPI.importImage(tempFilePaths[0])
        .then((res) => {
          uni.hideLoading();
          if (typeof res === "string") {
            const data = JSON.parse(res);
            if (data["status"] === 0) {
              delete data["data"]["role_id"];
              formData.userData = { ...formData.userData, ...data["data"] };
              popupRef.value.open();
            }
          }
        })
        .catch((err) => {
          uni.hideLoading();
        });
    },
  });
};

const handerChange = (value: string) => {
  switch (value) {
    case "cards":
      {
      }
      break;
    case "groups":
      {
      }
      break;
  }
};

const openModal = () => {
  modalRef.value.open();
};

const openCreateModal = () => {
  type.value = 0;
  popupRef.value.open();
};
</script>
<style scoped lang="scss">
.createChat {
  .createChatBox {
    padding: 0 0.5rem;
    min-height: calc(100vh - var(--tab-bar-height) - env(safe-area-inset-bottom));
    background-color: var(--primary-bg-color);
    .createChatHead {
      display: flex;
      margin-top: 0.5rem;
      & ::v-deep {
        .uv-button {
          height: 1.75rem;
          width: 3rem;
        }
      }
    }
    .list-card {
      // background-position: center center;
      margin-bottom: 50rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 0 24rpx;
      box-sizing: border-box;

      // 渐变边框 伪元素+透明边框
      // background: #fff;
      // border: 4rpx solid transparent;
      // background-clip: padding-box, border-box;
      // background-origin: padding-box, border-box;
      // background-image: linear-gradient(to right, #fff, #fff), linear-gradient(90deg, #8f41e9, #578aef);
      .item {
        width: 100%;
        height: 600rpx;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
      }
      .noData {
        color: $uni-text-color-grey;
        font-size: 0.8rem;
        margin-top: 1rem;
      }
    }
    .modalSelectBox {
      padding: 0 2rem;
      ::v-deep {
        .uv-upload__wrap {
          display: block;
        }
      }
      .exportDataStyle {
        margin: 1rem 0 2rem;
      }
    }
  }
  .list-card {
    // background-position: center center;
    margin-bottom: 50rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 0 24rpx;
    box-sizing: border-box;

    // 渐变边框 伪元素+透明边框
    // background: #fff;
    // border: 4rpx solid transparent;
    // background-clip: padding-box, border-box;
    // background-origin: padding-box, border-box;
    // background-image: linear-gradient(to right, #fff, #fff), linear-gradient(90deg, #8f41e9, #578aef);
    .item {
      width: 100%;
      height: 600rpx;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }
  }
  .modalSelectBox {
    padding: 0 2rem;
    ::v-deep {
      .uv-upload__wrap {
        display: block;
      }
    }
    .exportDataStyle {
      margin: 1rem 0 2rem;
    }
  }
}
.popupCreateBox {
  height: 100vh;
  box-sizing: border-box;
  padding: 0.75rem;
  display: flex;
  flex-direction: column;
  background-color: var(--primary-bg-color);
  .popupCreateForm {
    flex: 1;
    overflow-y: auto;
    ::v-deep {
      .uv-form-item__body__left__content__label,
      .uni-input-input,
      .uni-textarea-textarea {
        color: var(--color-background-lighter);
      }
    }
    .borderBox {
      border: 1px solid var(--border-color);
      background-color: transparent;
    }
    .baseInputHeight {
      height: 2rem;
    }
  }
  .popupCreateEmit {
  }
}
</style>
